import { defineStore } from 'pinia';

const useWebsocketStore = defineStore('websocketStore', {
  state: () => ({
    ws: null,
    wsConnect: false,
    resultMessage: "",
    logTail: true,
    monitoringMap: {},
    localhostPath: "",
    timer: null,
    completeInfo: ""
  }),
  getters: {

  },
  actions: {
    setLogTail (v) {
      this.logTail = v;
    },
    connect (localhostPath) {
      this.localhostPath = localhostPath;
      if (this.ws != null) {
        if (this.ws.readyState == 1) {
          return;
        }

      }
      if (typeof WebSocket === "undefined") {
        console.log("您的浏览器不支持WebSocket");
        return;
      }
      let url = localhostPath;
      // 打开一个websocket
      this.ws = new WebSocket(url);
      console.log(localhostPath)
      // 建立连接
      this.ws.onopen = () => {
        this.wsConnect = this.ws.readyState == 1 ? true : false;
        if (this.wsConnect) {
          console.log("连接成功");
        } else {
          this.wsConnect = false;
          console.log("连接失败");
        }
        this.timer = setInterval(() => {
          this.ws.send("ping");
          this.wsConnect = this.ws.readyState == 1 ? true : false;
        }, 10000);
      };
      this.ws.onmessage = evt => {
        let result;
        try {
          result = evt.data;
          if (result == "ping") {
            return;
          }
          this.resultMessage = result;
        } catch (e) {
          console.log(e)
        }
      };
      // 发生错误时
      this.ws.onerror = evt => {
        this.resultMessage = "";
      };
      // 关闭连接
      this.ws.onclose = evt => {
        console.log("关闭连接")
        clearInterval(this.timer);
        this.wsConnect = false;
        this.ws = null;
        setTimeout(() => {
          this.connect(this.localhostPath);
        }, 3000);
      };
    },
    close () {
      if (this.ws != null) {
        this.ws.close();
        this.logTail = false;
      }
    },
  },

})
export default useWebsocketStore